// vgoods/edit/index.js
var api = require("../../api.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    vgoods: null,
    video: null,
    goods_list: [],
    goods_count: 0,
    is_show_goods: !1,
    opacity_status: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      if (!options.id) {
        wx.navigateBack(-1)
        return ;
      }
      getApp().pageOnLoad(this, options);
      var that = this;
      getApp().request({
        url: getApp().api.vgoods.edit,
        data:{id: options.id},
        success: function (t) {
          if (0 == t.code) {
            that.setData({
              vgoods: t.data.vgoods,
              video: t.data.video,
              goods_list: t.data.goods_list,
              goods_count: t.data.goods_count,
              user_info: t.data.user_info,
              next_vgoods :t.data.next_vgoods,
              next_video :t.data.next_video,
              next_goods_list: t.data.next_goods_list,
              next_goods_count: t.data.next_goods_count,
              next_user_info: t.data.next_user_info,
            })
            that.xuanran_good(t.data.vgoods.id)
          }else {
            wx.showToast({
              icon: 'none',
              title: t.msg
            })
            setTimeout(function() {
              wx.navigateBack(-1)
            },1500)
          }
        }
      });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    getApp().pageOnShow(this);
    wx.getSystemInfo({
      success: function (res) {
          that.setData({
            statusBarHeight : res.statusBarHeight
          })
       }
    })
    this.cart_num();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var vgoods = this.data.vgoods;
    return {
      path: "/vgoods/edit/index?id=" + vgoods.id ,
      imageUrl: vgoods.cover_pic,
      title: vgoods.title,
      success: function (t) {
        
      },
    };
  },
  back: function () {

    //获取页面栈
    var pages = getCurrentPages();
    if(pages.length > 1){ //说明有上一页存在
      wx.navigateBack(-1)
    }else {
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  },
  update_show_goods() {
    var that = this;
    that.setData({
      is_show_goods: !that.data.is_show_goods
    })
  },
  // 获取购物车数量
  cart_num: function () {
    var that = this;
    wx.getStorage({
      key: 'user_info',
      success: function (res) {
        getApp().request({
          url: getApp().api.cart.list,
          success: function (t) {
            if (0 == t.code) {
              if (t.data.mch_list.length > 0) {
                var length = t.data.list.length + t.data.mch_list[0].list.length;
              } else {
                var length = t.data.list.length
              }
              that.setData({
                cart_num: length
              })
            }
          }
        });
      },
    })
  },
  xuanran_good: function(id) {console.log(id);
    var that = this;
    id = id + '';
    wx.getStorage({
      key: 'good_vgoods',
      success(res) {console.log(res)
        if (res.data.indexOf(id) > -1) {
          that.setData({
            is_good: 1
          })
        } else {
          that.setData({
            is_good: 0
          })
        }
        
      }
    })
  },
  good_Y: function(tt) {
    if (!wx.getStorageSync('user_info') || wx.getStorageSync('user_info').length == 0) {
      this.setData({
        user_info_show:!0
      })
      return false;
    }
    var posts_id = tt.currentTarget.dataset.id + '';
    var that = this;
    getApp().request({
      url: api.vgoods.good,
      method: "POST",
      data: {
        id: posts_id
      },
      success: function(t) {
        that.data.vgoods.good_num++;
        that.setData({
          vgoods: that.data.vgoods
        })
        wx.getStorage({
          key: 'good_vgoods',
          success(res) {
            res.data.push(posts_id);
            wx.setStorage({
              key: 'good_vgoods',
              data: res.data
            })
            that.setData({
              is_good: 1
            })
          },
          fail() {
            var arr = []
            arr.push(posts_id)
            wx.setStorage({
              key: 'good_vgoods',
              data: arr
            })
            that.setData({
              is_good: 1
            })
          }
        })
      }
    })
  },
  jia: function(t) {
    if (!wx.getStorageSync('user_info') || wx.getStorageSync('user_info').length == 0) {
      this.setData({
        user_info_show:!0
      })
      return false;
    }
    var that = this,
      o = t.currentTarget.dataset,
      r = that.data.goods_list;

    var goods_id = t.currentTarget.dataset.id;
    for (var s in r)
      if (parseInt(r[s].id) === parseInt(goods_id)) {
        var ee = r[s].num ? r[s].num + 1 : 1;
        if (r[s].id == goods_id) {
          var ss = s;
          wx.showLoading({
            title: "加载中"
          })
          var attr = JSON.parse(r[s].attr)[0].attr_list[0];
          getApp().request({
            url: api.cart.add_cart,
            method: "POST",
            data: {
              goods_id: parseInt(r[s].id),
              attr: '[{"attr_group_id":1,"attr_group_name":"规格","attr_id":' + attr.attr_id + ',"attr_name":"' + attr.attr_name + '"}]',
              num: 1
            },
            success: function(t) {
              wx.hideLoading();
              if (t.code == 0) {
                r[ss].c_num++;
                that.setData({
                  goods_list: r
                });
                wx.showToast({
                  icon: 'none',
                  title: t.msg,
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: t.msg,
                  duration: 1500
                })
              }
              that.cart_num();
            },
            complete: function(res) {
              wx.hideLoading()
            }
          })
        }
      }
  },
  showDialogBtn: function(o) {
    if (!wx.getStorageSync('user_info') || wx.getStorageSync('user_info').length == 0) {
      this.setData({
        user_info_show: !0
      })
      return false;
    }
    var r = this,
      i = o.currentTarget.dataset,
      goods_id = o.currentTarget.dataset.id;
    console.log(goods_id);
    wx.showLoading({
      title: "加载中"
    })
    getApp().request({
      url: api.default.goods,
      data: {
        id: goods_id
      },
      success: function(t) {
        wx.hideLoading()
        0 == t.code && (r.setData({
          currentGood: t.data,
          goods_name: t.data.name,
          attr_group_list: t.data.attr_group_list,
          showModal: !0
        }), r.resetData(), r.updateData());
      },
      complete: function() {
        wx.hideLoading()
      }
    });
  },
  attrClick: function(t) {
    var a = this,
      o = t.target.dataset.groupId,
      r = t.target.dataset.id,
      i = a.data.attr_group_list,
      s = a.data.currentGood;
    for (var e in i)
      if (i[e].attr_group_id == o)
        for (var d in i[e].attr_list) i[e].attr_list[d].attr_id == r ? i[e].attr_list[d].checked = !0 : i[e].attr_list[d].checked = !1;
    var c = [];
    for (var e in i)
      for (var d in i[e].attr_list) !0 === i[e].attr_list[d].checked && c.push([i[e].attr_list[d].attr_id, s.id]);
    var n = JSON.parse(a.data.currentGood.attr),
      u = a.data.temporaryGood;
    for (var _ in n) {
      var g = [];
      for (var l in n[_].attr_list) g.push([n[_].attr_list[l].attr_id, s.id]);
      if (g.sort().join() === c.sort().join()) {
        if (0 === parseInt(n[_].num)) return void wx.showToast({
          title: "商品库存不足",
          image: "/images/icon-warning.png"
        });
        u = parseFloat(n[_].price) ? {
          price: n[_].price.toFixed(2)
        } : {
          price: s.price.toFixed(2)
        };
      }
    }
    a.resetData(), a.checkUpdateData(c), a.setData({
      attr_group_list: i,
      temporaryGood: u,
      checked_attr: c
    });
  },
  resetData: function() {
    this.setData({
      checked_attr: [],
      check_num: 0,
      check_goods_price: 0,
      temporaryGood: {
        price: "0.00"
      }
    });
  },
  checkUpdateData: function(t) {
    var a = this,
      o = a.data.carGoods;
    for (var r in o) {
      var i = [];
      for (var s in o[r].attr) i.push([o[r].attr[s].attr_id, o[r].goods_id]);
      i.sort().join() === t.sort().join() && a.setData({
        check_num: o[r].num,
        check_goods_price: o[r].goods_price
      });
    }
  },
  onConfirm: function(t) {
    var a = this,
      o = a.data.attr_group_list,
      r = a.data.checked_attr,
      i = a.data.currentGood;
    if (r.length === o.length) {
      var s = a.data.check_num ? a.data.check_num + 1 : 1,
        e = JSON.parse(i.attr);
      for (var d in e) {
        var c = [];
        for (var n in e[d].attr_list)
          if (c.push([e[d].attr_list[n].attr_id, i.id]), c.sort().join() === r.sort().join()) {
            var u = e[d].price ? e[d].price : i.price,
              _ = e[d].attr_list;
            if (s > e[d].num) return void wx.showToast({
              title: "商品库存不足",
              image: "/images/icon-warning.png"
            });
          }
      }

      for (var ii in o) {
        for (var kk in o[ii].attr_list) {
          if (o[ii].attr_list[kk].checked) {
            o[ii].attr_id = o[ii].attr_list[kk].attr_id;
            o[ii].attr_name = o[ii].attr_list[kk].attr_name;
          }
        }
        delete o[ii].attr_list;
      }
      wx.showLoading({
        title: '加载中',
      })
      getApp().request({
        url: api.cart.add_cart,
        method: "POST",
        data: {
          goods_id: i.id,
          attr: JSON.stringify(o),
          num: 1
        },
        success: function(t) {
          if (t.code == 0) {
            wx.showToast({
              title: t.msg,
              duration: 1500
            });
            a.cart_num()
          }
        },
        complete: function() {
          wx.hideLoading()
        }
      })

      var g = a.data.carGoods,
        l = 1,
        h = (parseFloat(u) * s).toFixed(2);
      for (var p in g) {
        var f = [];
        for (var v in g[p].attr) f.push([g[p].attr[v].attr_id, g[p].goods_id]);
        if (f.sort().join() === r.sort().join()) {
          l = 0, g[p].num = g[p].num + 1, g[p].goods_price = (parseFloat(u) * g[p].num).toFixed(2);
          break;
        }
      }
      a.hideGoodsModel();
    } else wx.showToast({
      title: "请选择规格",
      image: "/images/icon-warning.png"
    });
  },
  updateData: function() {
    var t = this,
      a = t.data.currentGood,
      o = t.data.carGoods,
      r = JSON.parse(a.attr),
      i = a.attr_group_list;
    for (var s in r) {
      var e = [];
      for (var d in r[s].attr_list) e.push([r[s].attr_list[d].attr_id, a.id]);
      for (var c in o) {
        var n = [];
        for (var u in o[c].attr) n.push([o[c].attr[u].attr_id, o[c].goods_id]);
        if (e.sort().join() === n.sort().join()) {
          for (var _ in i)
            for (var g in i[_].attr_list)
              for (var l in e) {
                if (parseInt(i[_].attr_list[g].attr_id) === parseInt(e[l])) {
                  i[_].attr_list[g].checked = !0;
                  break;
                }
                i[_].attr_list[g].checked = !1;
              }
          var h = {
            price: o[c].price
          };
          return void t.setData({
            attr_group_list: i,
            check_num: o[c].num,
            check_goods_price: o[c].goods_price,
            checked_attr: e,
            temporaryGood: h
          });
        }
      }
    }
  },
  hideGoodsModel: function() {
    this.setData({
      showModal: !1
    });
  },
  close_box: function(t) {
    this.setData({
      showModal: !1
    });
  },
  get_goods_info: function(t) {
    var d = t.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/goods/goods?id=" + d
    });
  },
  get_cat_list: function () {
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function(e) {
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
    })
  },
  //手指结束 记录起点X坐标
  touchend: function (e) {
    this.setData({ translateY: 0 })

    var that = this;
    var endX= e.changedTouches[0].clientX;
    var endY= e.changedTouches[0].clientY;
    var startY = that.data.startY;
    that.setData({opacity_status: 1})
    if (startY - endY >= 150 && startY > 0) {
      that.setData({
        vgoods: that.data.next_vgoods,
        video: that.data.next_video,
        goods_list: that.data.next_goods_list,
        goods_count: that.data.next_goods_count,
        user_info: that.data.next_user_info,
      })
      that.xuanran_good(that.data.next_vgoods.id)

      getApp().request({
        url: getApp().api.vgoods.edit,
        data:{id: that.data.next_vgoods.id},
        success: function (t) {
          if (0 == t.code) {
            that.setData({
              next_vgoods :t.data.next_vgoods,
              next_video :t.data.next_video,
              next_goods_list: t.data.next_goods_list,
              next_goods_count: t.data.next_goods_count,
              next_user_info: t.data.next_user_info,
            })
          }else {
            wx.showToast({
              icon: 'none',
              title: t.msg
            })
            setTimeout(function() {
              wx.navigateBack(-1)
            },1500)
          }
        }
      });
    }
  },
  touchmove: function(e) {
    var that = this;
    var startX = that.data.startX; //开始X坐标
    var startY = that.data.startY; //开始Y坐标
    var touchMoveX = e.changedTouches[0].clientX; //滑动变化坐标
    var touchMoveY = e.changedTouches[0].clientY; //滑动变化坐标
    if (startY - touchMoveY <= 150 && startY > 0) {
        var opacity_status = (startY - touchMoveY) / 300
        // that.setData({opacity_status: (1 - opacity_status)})
    }else {
      // that.setData({opacity_status: 0.3})
    }
  },
})